package com.cy;

import java.util.LinkedList;
import java.util.List;

public abstract class SubStepAbstract implements Runnable{
    private final LinkedList<SubStepAbstract> childNodes = new LinkedList<>();
    private final LinkedList<SubStepAbstract> preNodes = new LinkedList<>();
    private boolean isSuccess = false;
    @Override
    public void run() {
        before();
        if (isRequiresFail()) {
            return;
        }
        doTask();
    }

    protected void before() {
        if (isRequiresFail()) {
            return;
        }
        if (this.hasChild()) {
            for (SubStepAbstract node : this.getChild()) {
                new Thread(node).start();
            }
        }
    }

    public void setSuccess(boolean bool){
        this.isSuccess = bool;
    }

    public boolean isRequiresFail() {
        for (SubStepAbstract node : this.getPreNodes()) {
            if (!node.isSuccess()) {
                return true;
            }
        }
        return false;
    }

    private LinkedList<SubStepAbstract> getPreNodes() {
        return preNodes;
    }

    private boolean isSuccess() {
        return isSuccess;
    }

    private LinkedList<SubStepAbstract> getChild() {
        return this.childNodes;
    }

    private boolean hasChild() {
        return !this.getChild().isEmpty();
    }

    protected abstract void doTask();

    public void setChild(SubStepAbstract child){
        this.childNodes.add(child);
    }

    public void preNode(SubStepAbstract parent){
        this.preNodes.add(parent);
    }
}
